﻿using System.Web;
using EPiServer;
using EPiServer.Core;
using OpenWaves.EPiServer.Abstractions;

namespace OpenWaves.EPiServer
{
    public static class HttpContextExtensions
    {
        public static PageData GetCurrentPage(this HttpContext context)
        {
            var templatePage = context.Handler as TemplatePage;
            if (templatePage != null)
                return templatePage.CurrentPage;

            // Request is not being handled by TemplatePage - try to resolve current page from the query string

            var pageReferenceString = context.Request.QueryString["id"];
            PageReference currentPageReference;
            if (PageReference.TryParse(pageReferenceString, out currentPageReference))
            {
                return ServiceLocator.Resolve<IDataFactory>().GetPage(currentPageReference, LanguageSelector.AutoDetect(true));
            }

            return null;
        }
    }
}